<?php

namespace App\Http\Controllers\Auth;

use App\Http\Models\Customer;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;

class WebAuthController extends Controller
{
    const VIEW_ADMIN_WEB_HOME = 'admin.web-home';
    const VIEW_ADMIN_LOGIN = 'admin.admin-website-login';

    use AuthenticatesAndRegistersUsers,
        ThrottlesLogins;

    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => ['logout']]);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return Customer::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

    /**
     * 后台登录view
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function webLogin()
    {
        if(Auth::guard('web-admin')->check()) {
            return view(self::VIEW_ADMIN_WEB_HOME);
        }

        return view(self::VIEW_ADMIN_LOGIN);
    }

    /**
     * 登录post
     *
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function webLoginPost(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
            'password' => 'required',
        ]);

        if (auth()->guard('web-admin')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')  ]))
        {
             auth()->guard('web-admin')->user();

            return redirect()->route('web-home');

        }else{
            return view(self::VIEW_ADMIN_LOGIN)->withErrors(['邮箱或密码输入有误，请重新输入!']);
        }
    }

    /**
     * 后台退出接口
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function webLogout()
    {
        auth()->guard('web-admin')->logout();

        return redirect()->route('web-login');
    }
}
